package dst.ass2.ejb.simulator;

import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TimerService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import dst.ass1.jpa.model.ITask;
import dst.ass1.jpa.model.ITaskProcessing;
import dst.ass1.jpa.model.TaskStatus;

@Singleton
@Startup
public class SimulatorBean {
	
	@Resource
    private TimerService timerService;

    @PersistenceContext
    private EntityManager entityManager;
    
    private final static Logger LOGGER = Logger.getLogger(SimulatorBean.class.getName());

    @Schedule(hour="*", minute = "*", second = "*/5")   //repeat every 5 seconds --> http://docs.oracle.com/javaee/6/api/javax/ejb/Schedule.html
    public void simulate() {
    	
    	//get all Tasks where Processing date end is null
    	TypedQuery<ITask> q = entityManager.createQuery("SELECT t FROM Task t JOIN t.taskProcessing p WHERE p.end IS null", ITask.class);
        List<ITask> tasks = q.getResultList();

        Date now = new Date();
        LOGGER.info("call simulate @ "+new Date());
        
        //for every task thats start state is in the past persist it
        for (ITask task : tasks) {
            if (task.getTaskProcessing().getStart().before(now)) {

            	ITaskProcessing taskProcessing = task.getTaskProcessing();  
            	int processingDuration=(int)((now.getTime() - taskProcessing.getStart().getTime())/1000);  //calculate the Duration for Processing

            	//setting values in TaskProcessing
                taskProcessing.setStatus(TaskStatus.FINISHED);   //set new Status 
                taskProcessing.setEnd(new Date());				//set the End Time
                
                //setting values in Task
                task.setProcessingTime(processingDuration);		//set the calculated Processing Time

                //persist
                entityManager.persist(task);					//persist the Task
                LOGGER.info("Task "+task.getId()+" finished");
                
            }
        }
    }

}
